/**
 * JWT请求过滤器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.security;


import com.sxf.crm.entity.User;
import com.sxf.crm.repository.UserRepository;
import org.springframework.lang.NonNull;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtRequestFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserRepository userRepository;

    @Override
    protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
        String path = request.getRequestURI();
        return path.startsWith("/api/auth/");
    }

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");
        logger.debug("Processing request: {} with Authorization header: {}", request.getRequestURI(), authorizationHeader);

        String username = null;
        String jwt = null;

        try {
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                jwt = authorizationHeader.substring(7);
                username = jwtTokenUtil.getUsernameFromToken(jwt);
                logger.debug("Extracted username from token: {}", username);
            }

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                User user = userRepository.findByUsername(username).orElse(null);
                if (user != null && jwtTokenUtil.validateToken(jwt, user)) {
                    logger.debug("User authenticated: {}, authorities: {}", 
                        user.getUsername(), 
                        user.getAuthorities().stream()
                            .map(auth -> auth.getAuthority())
                            .collect(Collectors.joining(", ")));
                    
                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                            user, null, user.getAuthorities());
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                    logger.debug("Security context updated with authentication for user: {}", username);
                } else {
                    logger.warn("Token validation failed for user: {}", username);
                    handleJwtValidationError(response, "Token验证失败");
                    return;
                }
            }
        } catch (ExpiredJwtException e) {
            logger.error("JWT Token已过期: {}", e.getMessage());
            handleJwtValidationError(response, "Token已过期");
            return;
        } catch (UnsupportedJwtException | MalformedJwtException e) {
            logger.error("不支持的JWT Token格式: {}", e.getMessage());
            handleJwtValidationError(response, "不支持的Token格式");
            return;
        } catch (IllegalArgumentException e) {
            logger.error("JWT Token参数错误: {}", e.getMessage());
            handleJwtValidationError(response, "Token参数错误");
            return;
        } catch (Exception e) {
            logger.error("JWT Token处理异常: {}", e.getMessage());
            handleJwtValidationError(response, "Token处理异常");
            return;
        }

        chain.doFilter(request, response);
    }

    private void handleJwtValidationError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        String jsonResponse = String.format("{\"status\":401,\"message\":\"%s\"}", message);
        response.getWriter().write(jsonResponse);
    }
}